import java.util.concurrent.CountDownLatch;

import org.junit.Test;

public class MyTest {

    private class Node{
        boolean judgement;
        int idx;
        /**
         * @param judgement
         * @param idx
         */
        public Node(boolean judgement, int idx) {
            this.judgement = judgement;
            this.idx = idx;
        }
        
    }

    @Test
    public void test1(){
        int[] gas={1,2,3,4,5};
        int[] cost={3,4,5,1,2};
        //System.out.println(judeg(gas, cost, 3).judgement);
        System.out.println(check(gas, cost, 1));        
    }

    private int check(int[] gas,int[] cost,int n){
        if(gas[0]<cost[0]) return -1;
        if(n==0) return -1;
        boolean judgement=judeg(gas, cost, n).judgement;
        int idx=judeg(gas, cost, n).idx;
        if(judgement) return n;
        else return check(gas, cost,idx+1);
    }

    private Node judeg(int[] gas,int[] cost,int start){
        int cur=gas[start];
        if(cur<cost[start]) return new Node(false, start);
        cur-=cost[start];
        int idx=(start+1)%gas.length;

        while(idx!=start){
            cur+=gas[idx]-cost[idx];
            if(cur<0) break;
            idx=(idx+1)%gas.length;
        }
        if(idx==start) return new Node(true, idx);
        else return new Node(false, idx);
    }
}
